package com.aop.proxy.cglib;

import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
    private Object target;
    private Class clazz;
    CglibProxy(Object o,Class clazz){
        this.target = o;
        this.clazz =clazz;
    }

    public Object getNewTarget(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(CglibProxy.this); ////通过回调指定代理类。
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("吃饭前--洗手");
        Object invoke = method.invoke(target, objects);
        System.out.println("吃饭后--洗手");
        return invoke;
    }


    public static void main(String[] args) {
        DayWork dayWork = new DayWork();
        CglibProxy cglibProxy = new CglibProxy(dayWork,DayWork.class);
        DayWork dayWorkProxy = (DayWork) cglibProxy.getNewTarget();
        dayWorkProxy.breakfast();
        dayWorkProxy.lunch();
        dayWorkProxy.dinner();
        //根据打印的东西不同来判断是jdk动态代理（$Proxy）还是cglib代理 （$EnhancerByCGLIB$）
        System.out.println(dayWorkProxy.getClass());
        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
    }
}
